<script>
  import { nextTick } from 'vue'
  import html2canvas from 'html2canvas'
  export default function () {
    // 返回base64及data
    const getBase64 = function (url) {
      return new Promise((resolve, reject) => {
        const img = new Image()
        img.setAttribute('crossOrigin', 'Anonymous')
        img.onload = function () {
          const base64 = getImgBase64(img)
          if (base64) {
            resolve(base64)
          } else {
            reject()
          }
          // return base64
        }
        img.src = url
      })
    }

    const getImgBase64 = function (img) {
      const canvas = document.createElement('canvas')
      canvas.width = img.width
      canvas.height = img.height
      var ctx = canvas.getContext('2d')
      ctx.drawImage(img, 0, 0, img.width, img.height)
      let idx = img.src.lastIndexOf('.')
      var ext = img.src.slice(idx + 1).toLowerCase()
      if (ext == 'jpg') ext = 'jpeg'
      var dataUrl = canvas.toDataURL('images/' + ext)
      return dataUrl
    }

    // html2canvas domId范围有图片 需要避免跨域 加useCORS: true 或者 转成base64
    const htmlToImg = async function (domId, cb) {
      window.pageYoffset = 0
      document.documentElement.scrollTop = 0
      document.body.scrollTop = 0
      await nextTick()
      html2canvas(document.getElementById(domId), {
        height: document.getElementById(domId).scrollHeight,
        windowHeight: document.getElementById(domId).scrollHeight,
        useCORS: true,
      }).then((canvas) => {
        const imgUrl = canvas.toDataURL('image/png')
        cb(imgUrl)
      })
    }
    return {
      getBase64,
      getImgBase64,
      htmlToImg,
    }
  }
</script>
